﻿//http启动脚本
"use strict";
const mvc = require('cosjs.mvc');
const cosjs = require('cosjs');
const body = require('body-parser');
const monitor = require('cosjs.monitor');

module.exports = function () {
    let app = this;
    app.defineHandlePrototype("model", mvc.model);
    app.defineHandlePrototype("config", mvc.config);
    app.defineHandlePrototype("library", mvc.library);

    let jsonencoded = body.json({ extended: true, limit: "100kb" });
    //内部服务器
    //let local_root = setting["root"] + '/handle/local';
    let local_route = { route: "/s:sid/*", method: 'all', output: 'json', "subpath": local_handle_subpath }
    let local_server = app.server(mvc.handle.local(), local_route, jsonencoded);
    local_server.on('start', local_handle_start);
    /////////////////////监控服务//////////////////////
    let spirit = mvc.config.get("spirit");
    if (spirit) {
        create_spirit_server.call(local_server, spirit);
    }
    //初始化SESSION配置，万一要用呢？
    let session = mvc.config.get("session") || {};
    session['redis'] = local_session_redis;
    session['level'] = 1;
    session['method'] = 'all';
    require("cosjs.session").config.set(session);
}

function local_handle_subpath() {
    this.sid = parseInt(this.req.params["sid"]) || 0;
    return this.req.params[0];
}
//本地验证
function local_handle_start() {
    let sid = mvc.config.get('sid');
    if (!this.sid || sid.indexOf(this.sid) < 0) {
        console.log("this is  local")
        return this.error("server_id_error", `game[${this.sid}] not in this server local`);
    }

    let debug = this.config.get('debug');
    if (debug >= 2) {
        return true;
    }
    let branch = mvc.config.get("branch");
    let { err, ret } = mvc.library.call(this, 'sign/verify', this.req.body, branch.secret);
    if (err) {
        return this.error(err, ret);
    }
}

function local_session_redis() {
    let sid = this.sid;
    let key = ["cache", sid].join("");
    let redis = cosjs.pool.get(key);
    if (!redis) {
        throw new Error(`session redis[${key}] empty`)
    }
    return redis;
}


function create_spirit_server(spirit) {
    let server = spirit.server;
    let branch = mvc.config.get("branch");
    let update = spirit.update;

    server.branch = branch.id;
    server.secret = branch.secret;
    update.sid = mvc.config.get('sid');
    update.url = mvc.config.get('remote.url') || '';
    update.local = mvc.config.get('local.port');
    update.remote = mvc.config.get('remote.port') || 80;
    return Promise.resolve().then(() => {
        console.log("server,update---------", server, update)
        return monitor.spirit(server, update);
    }).then(() => {
        console.log("monitor.handle,spirit.route---------", monitor.handle, spirit.route)
        return this.loader.addFile(monitor.handle, spirit.route);
    }).catch(err => {
        console.log("create_spirit_server", err)
    })
}